<?php
/**
 * Easthv Zend Framework Project
 *
 *
 * LICENSE:
 *
 * @category   Zend
 * @package    Zend_Helper
 * @copyright  Copyright (c) 2009-2010 Easthv Team @ East Hui Van Business Consulting Co., Ltd.(http://www.easthv.com)
 * @license    http://framework.zend.com/license/   BSD License
 * @version    1.0
 * @link       http://www.easthv.com
 * @since      1.0
*/

/**
 * Core Helper Class
 *
 * @category   Zend
 * @package    Zend_Helper
 * @copyright  Copyright (c) 2009-2010 Easthv Team @ East Hui Van Business Consulting Co., Ltd.(http://www.easthv.com)
 * @license    http://framework.zend.com/license/   BSD License
 * @version    1.0
 * @link       http://www.easthv.com
 * @since      1.0
 * @deprecated
 */
class Zend_View_Helper_Easy
{
    /**
     * @var object Zend_View
     */
    public $view;

    /**
     * Set Zend View
     *
     *
     * @param  Zend_View_Interface   $view   zend view interface 
     *
     * @access public
     *
     * @return void
     */
    public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;

        if (!$this->view->config || !$this->view->setting || !$this->view->webroot) {
            $config = Zend_Registry::get('config');
            $this->view->config = $config['system'];
            $this->view->setting = $config['system']['content'];
            $this->view->webroot = isset($config['resources']['frontController']['baseUrl']) ? $config['resources']['frontController']['baseUrl'] : '';
        }
    }

    /**
     * Helper core function
     *
     * @param string $path
     * @param mixed $callback boolean or string
     *              when boolean is true,current url will be postfix of path
     *              when string, $callback will be postfix of path
     * @param param $param postfix param name
     *
     * @access public
     *
     * @return mixed     if path was set, return escaped path string
     *                   if path was not set, return Zend_View_Helper object
     */
    public function Easy($path = '', $callback = false, $param = 'jumpto')
    {
        if (0 == func_num_args()) {
            return $this;
        }

        if ($callback) {
            $url = $callback === true ? $this->getCurrentUrl() : $callback;
            $url = $param . '=' . str_replace('/', '-', str_replace('+', '*', base64_encode(gzcompress($url)) ) );
            $path = strpos($path,'?') === false ? $path . '?' . $url : $path . '&' . $url;
        }

        return $this->view->escape($this->view->webroot . $path);
    }
    
    /**
     * Get escaping path string with url params
     *
     * @param string $path
     * @param mixed $callback boolean or string
     *              when boolean is true,current url will be postfix of path
     *              when string, $callback will be postfix of path
     * @param param $param postfix param name
     *
     * @access public
     *
     * @return mixed     
     *                   
     */
    public function g($path = null, $callback = false, $param = 'jumpto')
    {    
        if (!$this->view->grid && !is_array($path[1])) {
            return $this->Easy($path,$callback,$param);
        }

        $params = $this->view->grid;

        if ($path && is_array($path)) {
            foreach($path[1] as $key => $value) {
                $params[$key] = $value;
            }
            $path = $path[0];
        }


        return $path
            ? $this->Easy( $path . '?' . $this->_paramArrayToString($params) )
            : $this->getCurrentPath() . '?' . $this->_paramArrayToString($params);
    
    }

    /**
     * Escape url with static domain, to keep cookie free
     *
     * @param string $path
     * @param mixed $callback boolean or string
     *              when boolean is true,current url will be postfix of path
     *              when string, $callback will be postfix of path
     * @param param $param postfix param name
     *
     * @access public
     *
     * @return mixed     if path was set, return escaped path string
     *                   if path was not set, return false
     */
    public function s($path = null, $callback = false, $param = 'jumpto')
	{
		return $this->view->config['domain']['static'] ? 
			$this->view->config['domain']['static'] . $this->Easy($path, $callback, $param)
            : $this->Easy($this->view->config['dir']['prefix'] . $path, $callback, $param) ;
    }
    
    /**
     * Get escaping full URL
     *
     * @param string $path
     * @param mixed $callback boolean or string
     *              when boolean is true,current url will be postfix of path
     *              when string, $callback will be postfix of path
     * @param param $param postfix param name
     *
     * @access public
     *
     * @return mixed     
     *                   
     */
    public function f($path = null, $callback = false, $param = 'jumpto')
    {
        if (isset($this->currentRoot) && $this->currentRoot) {
        
            $base = $this->currentRoot;

        } else {

            $base = $this->currentRoot = (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443 ? 'https://' : 'http://') 
                . ($this->view->config['domain']['main']['name'])
                . ($_SERVER['SERVER_PORT'] == '80' || $_SERVER['SERVER_PORT'] == 443  ? '' : ':'.$_SERVER['SERVER_PORT']);

        }

        return $base . $this->Easy($path, $callback, $param);
    
    }

   
    /**
     * Simple L10N function
     *
     *
     * @param  string $name     
     * @param  string $default     
     *
     * @access public
     *
     * @return mixed
     */
    public function options($name, $default = null)
    {
        if (!$name) {
            return;
        }

        if ($this->view->config['cache']['option']) {
            
            $cache = Zend_Cache::factory('Core', 'File',array(
                'lifeTime' => 7200,
                'automatic_serialization' => true
                ),
                array(
                    'cache_dir' => APPLICATION_PATH . $this->view->config['path']['cache']['option']
                )
            );    
        
            //load cache ,if cache exist,return res;
            if ($cache->load($name)) {
                return $cache->load($name);
            }
        }
        
        switch ($name)
        {
            case 'days':
                for($i = 1; $i <=31; $i++){
                    $datas[] = array($i,$i);
                }
                break;
            case 'years' :
                $plus = 150;
                
                $year = gmdate("Y",time());

                if($plus > 0){
                    for($i = 0; $i <= $plus; $i++){
                        $datas[] = array($year - $i,$year - $i);
                    }
                } else {
                    for($i = 0; $i >= $plus; $i--){
                        $datas[] = array($year - $i,$year - $i);
                    }
                }
                break;
            default : 
                $value = file_get_contents(APPLICATION_PATH . $this->view->config['path']['option'] . $name . '/' . $this->view->language . '/' . $name);
                
                if (!$value) {
                
                    $value = file_get_contents(APPLICATION_PATH . $this->view->config['path']['option'] . $name . '/en/' . $name);
                }
                    
                $datas = Zend_Json::decode($value);
        }
    
        if ($default) {
            $res[] = $default;
        }    
        
        foreach($datas as $data){
            $res[] = $data;
        }
        
        if ($this->view->config['cache']['option'] && $res) {
            //save to cache
            $cache->save($res,$name);
        }
        
        return $res;
    }    

    /**
     * Get Current Full Path
     * Content Controller, Action, id
     *
     * 
     * @access public
     *
     * @return string Current Path string
     */
    public function getCurrentPath($withQuery = false)
    {
        $arrUrl = parse_url($_SERVER['REQUEST_URI']);
        $queryString = $arrUrl['query'];
        return $withQuery === false && $queryString ? substr($queryString, 0, -strlen($queryString) - 1) : $_SERVER['REQUEST_URI'];
    }

    /**
     * Get Current Full Url
     *
     * 
     * @access public
     *
     * @return string Current url string
     */
    public function getCurrentUrl($withQuery = true)
    {
        if ($this->view->currentUrl) {

            return $this->view->currentUrl;

        }

        $base = (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443 ? 'https://' : 'http://') 
            . ($_SERVER['SERVER_NAME'])
            . ($_SERVER['SERVER_PORT'] == '80' || $_SERVER['SERVER_PORT'] == 443  ? '' : ':'.$_SERVER['SERVER_PORT']);

        $base =  $base . $this->getCurrentPath($withQuery);

        return $this->view->currentUrl = $base;

    }

    /**
     * Generates grid field link
     *
     * @param  string $sortby    grid field order name
     *
     * @access public
     *
     * @return string   grid link
     */
    public function gridField($sortby, $path = null, $order = "desc")
    {
        if (!$this->view->grid) {

            return $path ? $this->Easy(  $path . '?' . $this->_paramArrayToString(array('sortby' => $sortby , 'order' => $order))  )
                : $this->getCurrentPath() . '?' . $this->_paramArrayToString(array('sortby' => $sortby , 'order' => $order));

        }

        $params = $this->view->grid;

        if ($sortby == $params['sortby']) {
            $params['order'] = isset($params['order'])
                ? ($params['order'] == 'desc' ? 'asc' : 'desc')
                : $order;
        }

        $params['sortby'] = $sortby;
        
        return $path
            ? $this->Easy( $path . '?' . $this->_paramArrayToString($params) )
            : $this->getCurrentPath() . '?' . $this->_paramArrayToString($params);

    }

    /**
     * Generates grid field link mark
     *
     * @param  string $sortby    grid field order name
     * @param  boolean $reverse  swap mark
     * @param  string $markAsc   grid field ASC order mark 
     * @param  string $markDesc  grid field DESC order mark 
     *
     *
     * @access public
     *
     * @return string   grid link mark
     */
    public function gridFieldMark($sortby, $reverse = false, $markAsc = '▲', $markDesc = '▼')
    {
        if (!isset($this->view->grid['sortby']) || $sortby != $this->view->grid['sortby']) {
            return;
        }

        if ($reverse === true) {
            $tmp = $markAsc;
            $markAsc = $markDesc;
            $markDesc = $tmp;
        }

        return $this->view->grid['order'] == 'desc' ? $markAsc : $markDesc;
    }

    /**
     * Trans paginator params to string
     *
     * @param  array  $page    page number
     * @param  string $path      base url path 
     *
     *
     * @access public
     *
     * @return string   param string
     */
    public function pagerParam($page = null, $path = null)
    {
        $page = $page ? $page : 1;
        $params = $this->view->grid;
        $params['page'] = $page;
        //ksort($params);

        return $path ? $this->Easy( $path . '?' . $this->_paramArrayToString($params) ) : $this->getCurrentPath() . '?' . $this->_paramArrayToString($params) ;
    }

    /**
     * show valid messages
     *
     *
     * @access public
     *
     * @return string   valid messages
     */
    public function showValidMessage()
    {
        $res = $this->view->valids;

        $string = '<ul><li>';

        foreach($res as $key => $li) {

            $string .= count($li) > 1 ? implode('</li><li>',$li) : ($li[0] . '</li><li>');

        }

        return $string . '</li></ul>';
    }

    /**
     * Trans array to url string
     *
     * @param  array $arrs  arrays to transform
     *
     * @access public
     *
     * @return string   url string
     */
    private function _paramArrayToString($arrs)
    {
        if (!$arrs) {
            return;
        }

        $res = array();
        foreach($arrs as $key => $arr) {
            if (is_array($arr)) {
                foreach($arr as $_arr)    {
                    $res[] = $key . '[]=' . $_arr;
                }
            } else {
                $res[] = $key . '=' . $arr;
            }
        }
        
        $res = implode ('&',$res);
        return $res;
    }

    /**
     * Gravatar web service
     *
     * @param  string $email  email address
     * @param  int $size face image size
     *
     * @access public
     *
     * @return string   url string
     */
    public function userFace($email, $size = 60,$default = '/skins/images/noface_male.gif')
    {
        $gravUrl = "http://www.gravatar.com/avatar.php?".
            "gravatar_id=".md5( strtolower($email) ).
            "&amp;size=".$size."&amp;";

        return $gravUrl;

    }

    /**
     * Google analytics
     *
     * @param  string $code  tracker code
     *
     * @access public
     *
     * @return string  analytics js code
     */
    public function analytics($code = null)
    {
        if (!$this->view->config['3rd']['google']['analytics']['enable']) {
            return;
        }

        $code = $code ? $code : $this->view->config['3rd']['google']['analytics']['tracker'];

		$domain = $this->view->config['domain']['main']['name'];


		return "<script type=\"text/javascript\">var _gaq = _gaq || []; _gaq.push(['_setAccount', '$code']);_gaq.push(['_setDomainName', '.$domain']);_gaq.push(['_trackPageview']);(function(){var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);})();</script>";
    
    }

    /**
     * Check current url whether match url params
     *
     * @param  string $code  tracker code
     *
     * @access public
     *
     * @return string  analytics js code
     */
    public function checkCurrent($current, $string = 'current')
    {
        return in_array($this->view->params['action'] . $this->view->params['resource'],$current) === true ? $string : '';
    }

    /**
     * Compress all css file into one
     *
     *
     * @access public
     *
     * @return string   css html tag
     */
    public function cssCompressor()
    {
        $num = func_num_args();
        if ($num < 2) {
            return;
        }
        
        $params = func_get_args();

        $newName = $params[0];
        $debug = $this->view->config['debug'];
        $ext = !$debug ? '.min.css' : '.css';
        unset($params[0]);

        if ($num == 2) {
            return $debug ? $this->_css($params[1] . $ext) : $this->_css($params[1] . $ext ,$this->view->setting['version']);
        }

        $res = '';

        foreach($params as $param) {

            $res .= $this->_css($param . $ext);

        }

        if ($debug) {

            return $res;
        
        }

        $jsfile = $this->_getCssPath($newName . $ext);
        
        if (file_exists($jsfile)) {

            return $this->_css($newName . $ext,$this->view->setting['version']);
        
        }

        if (!$handle = fopen($jsfile, 'w+')) {

            return $res;

        }

        foreach($params as $param) {

            fwrite($handle, file_get_contents($this->_getCssPath($param . $ext)));

        }
        fclose($handle);

        

        return $this->_css($newName . $ext,$this->view->setting['version']);
    }

    /**
     * Get css file real path
     *
     * @param string $name css file name
     *
     * @access private
     *
     * @return string   css file path
     */
    private function _getCssPath($name = null)
    {

        return APPLICATION_PATH . '/../public' . $this->view->config['dir']['prefix'] . $this->view->config['dir']['css'] . $name;
    
    }

    /**
     * Get css html tag
     *
     * @param string $name css file name
     * @param string $version system version (to clear cache)
     *
     * @access private
     *
     * @return string   css file path
     */
    private function _css($name, $version = null)
    {
        $version = $version ?  "?v=" . $version : '';
        return '<link href="' . $this->s($this->view->config['dir']['css'] .  $name . $version ) . '" media="all" rel="stylesheet" type="text/css" />';
    }

    /**
     * Compress all js file into one
     *
     *
     * @access public
     *
     * @return string   js html tag
     */
    public function jsCompressor()
    {
        $num = func_num_args();
        if ($num < 2) {

            return;

        }
        
        $params = func_get_args();

        $newName = $params[0];
        $debug = $this->view->config['debug'];
        $ext = !$debug ? '.min.js' : '.js';
        unset($params[0]);

        if($num == 2 && $newName == $params[1]) {

            return $this->_js($newName . $ext);
        
        }

        $res = '';

        foreach($params as $param) {

            $res .= $this->_js($param . $ext);

        }

        if ($debug) {

            return $res;
        
        }

        $jsfile = $this->_getJsPath($newName . $ext);
        
        if (file_exists($jsfile)) {

            return $this->_js($newName . $ext,$this->view->setting['version']);
        
        }

        if (!$handle = fopen($jsfile, 'w+')) {

            return $res;

        }

        foreach($params as $param) {

            fwrite($handle, file_get_contents($this->_getJsPath($param . $ext)));

        }
        fclose($handle);

        

        return $this->_js($newName . $ext,$this->view->setting['version']);
    }

    /**
     * Get js file real path
     *
     * @param string $name css file name
     *
     * @access private
     *
     * @return string  js file path
     */
    private function _getJsPath($name = null)
    {

        return APPLICATION_PATH . '/../public' . $this->view->config['dir']['javascripts'] . $name;
    
    }

    /**
     * Get js html tag
     *
     * @param string $name js file name
     * @param string $version system version (to clear cache)
     *
     * @access private
     *
     * @return string   js file path
     */
    private function _js($name, $version = null)
    {
        $version = $version ?  "?v=" . $version : '';
        return '<script type="text/javascript" src="' . $this->s($this->view->config['dir']['javascripts'] .  $name . $version ) . "\"></script>\n";
    }
    
    /**
     * Create google ajax api codes
     *
     * 
     * @access public
     *
     * @return string
     */
    public function googleApi()
    {
        return $this->view->config['3rd']['google']['api']['enable'] ? 
            '<script type="text/javascript" src="http://www.google.com/jsapi?key=' . $this->view->config['3rd']['google']['api']['key'] . "\"></script>\n"
            : '';
    
    }
    


	public function currency()
	{
        return $this->view->config['logic']['currency'] == 'USD' ? '$' : '￥';
    }

    /**
     * format a number to a price with currency
     *
     * 
     * @param float    $price       price to be format 
     * @param boolean  $showSymbol  whether show currency symbol 
     *
     * @access public
     *
     * @return float   price after format
     */
    public function price($price = null, $showSymbol = true)
    {
        $showSymbol = $this->view->config['logic']['currencyDisplay'];
        return $showSymbol ? $this->currency() . sprintf("%.2f",$price) : sprintf("%.2f",$price);
    }

	public function words($number, $singular, $plural = null)
	{
		if($number <= 1){
			return $this->view->I18N($singular);
		}

		return $plural ? $this->view->I18N($plural) : $this->view->I18N($singular . 's');
	}
  
	/**
     * Get xml text
     *
     * 
     * @param array $arr
     *
     *
     * @access public
     *
     * @return string
     */
	public function getXmlFormArray($arr)
	{
		if (!$arr) {
			return '';
		}
	
		foreach ($arr as $key=>$value) {
			if (!$value) {
				continue;
			}
			$xml .= "<$key>$value</$key>";

		}
		
		return $xml;
	}
}
